let prefix = "/dept";

$(function () {
    let options = {
        id: "bootstrap-tree-table",
        type: 1, // 0 代表bootstrapTable 1代表bootstrapTreeTable
        height: 0,
        rootIdValue: null,
        ajaxParams: {},
        toolbar: "toolbar",
        striped: false,
        expandColumn: 1,
        showSearch: true,
        showRefresh: true,
        showColumns: true,
        expandAll: true,
        expandFirst: true,
        code: "deptId",
        parentCode: "parentId",
        uniqueId: "deptId",
        url: "/dept/list",
        createUrl: "/dept/add/{id}",
        updateUrl: "/dept/edit/{id}",
        removeUrl: "/dept/remove/{id}",
        modalName: "部门",
        columns: [{
            field: 'selectItem',
            radio: true
        },
            {
                field: 'deptName',
                title: '部门名称',
                align: "left"
            },
            {
                field: 'orderNum',
                title: '排序',
                align: "left"
            },
            {
                field: 'status',
                title: '状态',
                align: "left",
                formatter: function (value) {
                    if (value === "0") {
                        return "<span class='badge badge-primary'>正常</span>"
                    } else {
                        return "<span class='badge badge-danger'>停用</span>"
                    }
                }
            },
            {
                field: 'createTime',
                title: '创建时间',
                align: "left"
            },
            {
                title: '操作',
                align: 'left',
                formatter: function (value, row) {
                    if (row.parentId !== 0) {
                        let actions = [];
                        actions.push('<a class="btn btn-success btn-xs" href="javascript:void(0)" onclick="edit(\'' + row.deptId + '\')"><i class="fa fa-edit"></i>编辑</a>');
                        actions.push('<a class="btn btn-info  btn-xs" href="javascript:void(0)" onclick="add(\'' + row.deptId + '\')"><i class="fa fa-plus"></i>新增</a>');
                        actions.push('<a class="btn btn-danger btn-xs" href="javascript:void(0)" onclick="remove(\'' + row.deptId + '\')"><i class="fa fa-trash"></i>删除</a>');
                        return actions.join('');
                    } else {
                        return "";
                    }
                }
            }]
    };

    $('#bootstrap-tree-table').bootstrapTreeTable({
        code: options.code,                                 // 用于设置父子关系
        parentCode: options.parentCode,                     // 用于设置父子关系
        type: 'post',                                       // 请求方式（*）
        url: options.url,                                   // 请求后台的URL（*）
        data: options.data,                                 // 无url时用于渲染的数据
        ajaxParams: options.ajaxParams,                     // 请求数据的ajax的data属性
        rootIdValue: options.rootIdValue,                   // 设置指定根节点id值
        height: options.height,                             // 表格树的高度
        expandColumn: options.expandColumn,                 // 在哪一列上面显示展开按钮
        striped: options.striped,                           // 是否显示行间隔色
        bordered: false,                                    // 是否显示边框
        toolbar: '#' + options.toolbar,                     // 指定工作栏
        showSearch: options.showSearch,                     // 是否显示检索信息
        showRefresh: options.showRefresh,                   // 是否显示刷新按钮
        showColumns: options.showColumns,                   // 是否显示隐藏某列下拉框
        expandAll: options.expandAll,                       // 是否全部展开
        expandFirst: options.expandFirst,                   // 是否默认第一级展开--expandAll为false时生效
        columns: options.columns,                           // 显示列信息（*）
        responseHandler: responseHandler,                   // 在加载服务器发送来的数据之前处理函数
        onLoadSuccess: onLoadSuccess                        // 当所有数据被加载时触发处理函数
    });

    function responseHandler(res) {
        if (typeof options.responseHandler == "function") {
            options.responseHandler(res);
        }
        if (res.code !== undefined && res.code !== 0) {
            console.log(res.msg);
            return [];
        } else {
            return res;
        }
    }

    // 当所有数据被加载时触发
    function onLoadSuccess(data) {
        if (typeof options.onLoadSuccess == "function") {
            options.onLoadSuccess(data);
        }
        $(".table [data-toggle='tooltip']").tooltip();
    }

    // tree表格树 展开/折叠
    let expandFlag;
    $("#expandAllBtn").click(function () {
        let dataExpand = isEmpty(options.expandAll) ? true : options.expandAll;
        expandFlag = isEmpty(expandFlag) ? dataExpand : expandFlag;
        if (!expandFlag) {
            $("#bootstrap-tree-table").bootstrapTreeTable('expandAll');
        } else {
            $("#bootstrap-tree-table").bootstrapTreeTable('collapseAll');
        }
        expandFlag = !expandFlag;
    });
});

//搜索
tableSearch = function () {
    let params = formToJSON('dept-form');
    $("#bootstrap-tree-table").bootstrapTreeTable('refresh', params);
}

//重置
tableReset = function () {
    $("#dept-form")[0].reset();
    $("#bootstrap-tree-table").bootstrapTreeTable('refresh', []);
}

//添加
function add(id) {
    layer.open({
        type: 2,
        area: ['800px', '800px'],
        fix: false,
        //不固定
        maxmin: true,
        shade: 0.3,
        title: "添加部门",
        content: prefix + "/add/" + id,
        btn: ['确定', '关闭'],
        // 弹层外区域关闭
        shadeClose: true,
        yes: function (index, layero) {
            let iframeWin = layero.find('iframe')[0];
            iframeWin.contentWindow.add(index, layero);
            $("#bootstrap-tree-table").bootstrapTreeTable('refresh', {silent: true});
        },
        cancel: function () {
            return true;
        }
    });
}

//修改
function edit(roleId) {
    let getRows = $("#bootstrap-tree-table").bootstrapTreeTable("getSelections");
    if (getRows.length !== 1 && typeof (roleId) == "undefined") {
        layer.alert("请选择一条记录", {
            icon: "warning",
            title: "系统提示",
            btn: ['确认'],
            btnclass: ['btn btn-primary'],
        });
    } else {
        let id;
        if (typeof (roleId) == "undefined") {
            id = getRows[0].deptId;
        } else {
            id = roleId
        }

        layer.open({
            type: 2,
            area: ['800px', '800px'],
            fix: false,
            //不固定
            maxmin: true,
            shade: 0.3,
            title: "修改部门",
            content: prefix + "/edit/" + id,
            btn: ['确定', '关闭'],
            // 弹层外区域关闭
            shadeClose: true,
            yes: function (index, layero) {
                let iframeWin = layero.find('iframe')[0];
                iframeWin.contentWindow.editRow(index, layero);
                $("#bootstrap-tree-table").bootstrapTreeTable('refresh', {silent: true});
            },
            cancel: function () {
                return true;
            }
        });
    }
}


// 删除信息
function remove(id) {
    confirm("确定删除该条信息吗？", function () {
        $.ajax({
            type: 'GET',
            url: prefix + "/remove/" + id,
            success: function (result) {
                if (result.code === 0) {
                    $("#bootstrap-tree-table").bootstrapTreeTable('refresh', {silent: true});
                }
            }
        });
    });
}


//改变状态
function changeStatus(that) {
    if (!that.hasClass('checked')) {
        let checked = $(".checked");
        checked.find('input').eq(0).removeAttr("checked");
        checked.removeClass('checked');


        that.find('input').eq(0).prop("checked", true);
        that.addClass('checked');
    }
}

// 确认窗体
confirm = function (content, callBack) {
    layer.confirm(content, {
        icon: 3,
        title: "系统提示",
        btn: ['确认', '取消']
    }, function (index) {
        layer.close(index);
        callBack(true);
    });
}



